package com.biostime.rpc.terminal.util;

import org.slf4j.Logger;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * <p>
 * 打印日志工具类
 * </p>
 *
 * @author yangrzh 2014/7/24
 */
public class LogUtils {

    public static void info(final Logger log, String funName, Object... params) {
        log.info(getLogString(funName, params));
    }

    public static void error(final Logger log, final Exception e, String funName, Object... params) {
        log.error(getLogString(funName, params), e);
    }

//    public static void main(String[] args) {
//        List<String> list = new ArrayList<String>();
//        list.add("sdfds");
//        list.add("123");
//
//        Map<String, List> map = new HashMap<String, List>();
//        map.put("123", list);
//        map.put("3424", list);
//        System.out.println(getLogString("good", 234, "OK", list, map));
//    }

    private static String getLogString(String funName, Object... params) {
        StringBuilder sb = new StringBuilder();
        sb.append(funName);
        sb.append("\t");
        for (Object o : params) {
            append(sb, o);
            sb.append(" ");
        }
        return sb.toString();
    }

    private static void append(final StringBuilder sb, Object o) {
        if (o instanceof List) {
            List list = (List) o;
            sb.append("[");
            for (Object to : list) {
                append(sb, to);
                sb.append(", ");
            }
            int length = sb.length();
            sb.delete(length - 2, length);
            sb.append("]");
        } else if (o instanceof Set) {
            Set set = (Set) o;
            sb.append("[");
            for (Object to : set) {
                append(sb, to);
                sb.append(", ");
            }
            int length = sb.length();
            sb.delete(length - 2, length);
            sb.append("]");
        } else if (o instanceof Map) {
            Map map = (Map) o;
            Set<Map.Entry> entrySet = map.entrySet();
            Iterator<Map.Entry> it = entrySet.iterator();
            sb.append("{");
            while (it.hasNext()) {
                Map.Entry entry = it.next();
                append(sb, entry.getKey());
                sb.append(":");
                append(sb, entry.getValue());
                sb.append(", ");
            }
            int length = sb.length();
            sb.delete(length - 2, length);
            sb.append("}");
        } else {
            sb.append(o);
        }
    }

}
